﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
using Ppt = Microsoft.Office.Interop.PowerPoint;
using ObjectModel.PowerPoint.RulesModel;

namespace ObjectModel.PowerPoint
{
    public static class ShapeExtensions
    {        
        public static void AlignTo(this Ppt.Shape shapeToAlign, object target, Offsets offsets,
            Alignment shapeAlign = Alignment.Centre, Alignment targetAlign = Alignment.Centre)
        {
            Offsets shapeOffsets = shapeToAlign.GetAlignmentOffset(shapeAlign);
            Offsets targetOffsets = target.GetAlignmentOffset(targetAlign);

            shapeToAlign.Top = ((dynamic)target).Top + targetOffsets.Y - shapeOffsets.Y + offsets.Y;
            shapeToAlign.Left = ((dynamic)target).Left + targetOffsets.X - shapeOffsets.X + offsets.X;
        }
        
        public static void AssignKey(this Ppt.Shape shape, int key)
        {
            shape.Tags.Add("Key", key.ToString());
        }

        public static Ppt.Shape CopyTo(this Ppt.Shape shape, Ppt.Slide slide)
        {
            shape.Copy();
            Ppt.ShapeRange shr = slide.Shapes.Paste();
            
            return shr[0];
        }

        public static string GetUniqueID(this Ppt.Shape shape)
        {
            return GetUniqueID(shape.GetSlide().SlideID, shape.Id);
        }

        public static string GetUniqueID(this Ppt.Shape shape, Ppt.Slide slide)
        {
            return GetUniqueID(slide.SlideID, shape.Id);
        }

        /// <summary>
        /// Returns a unique string ID from a slide ID and a shape ID. Ensures that all
        /// types that use this ID construct it in the same way.
        /// </summary>
        /// <param name="slideId"></param>
        /// <param name="shapeId"></param>
        /// <returns></returns>
        public static string GetUniqueID(int slideId, int shapeId)
        {
            return slideId.ToString() + "." + shapeId.ToString();
        }

        public static Ppt.Slide GetSlide(this Ppt.Shape shape)
        {
            // Note: this may need to be revised to something more robust, e.g. return shape.GetParent<Ppt.Slide>();
            return shape.Parent as Ppt.Slide;
        }

        public static bool IsSelected(this Ppt.Shape shape)
        {
            Ppt.Application app = shape.Application;
            Ppt.Selection sel = app.ActiveWindow.Selection;

            foreach (Ppt.Shape sh in sel.ShapeRange)
                if (shape == sh)
                    return true;

            return false;
        }

        public static Ppt.Shape FindById(this Ppt.Shapes shapes, int Id)
        {
            foreach (Ppt.Shape sh in shapes)
                if (sh.Id == Id)
                    return sh;

            return null;
        }
    }
}
